//
//  VisitDetailViewController.m
//  Marketing
//
//  Created by wmm on 16/3/4.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "VisitDetailViewController.h"
#import "VisitModel.h"
#import "Toast+UIView.h"
#import "MapClientViewController.h"
#import "SignInViewController.h"
#import "SignInSelectViewController.h"
#import "SVProgressHUD.h"
#import "DateTools.h"

//动画时间
#define kAnimationDuration 0.2
//键盘
#define kViewHeight 56
#define CELLHEIGHT4 50.0f

@interface VisitDetailViewController ()
{
    NSArray    *_basicArray;
    NSArray    *_dataArray;
    UIScrollView * scrollView;
    UIView *checkBG;
    
    UIView *upBgView;
    UIView *signView;
    UIView *downBgView;
    
    CGFloat  diff;
    NSInteger number;
    BOOL canEdit;
    
    CGFloat lon;
    CGFloat lat;
    
    int isSignin;
    int isSignout;
    
    UILabel *remaind;
    UIView *DownbgView;
    BOOL isEditing;
    UIView *line2;
    UITextView *endContent;
    BOOL isAge;
}

@property(nonatomic,strong)UILabel    *visitDateLbl;
@property(nonatomic,strong)UILabel    *companyLbl;
@property(nonatomic,strong)UILabel    *visitObjectLbl;
@property(nonatomic,strong)UILabel    *visitTypeLbl;
@property(nonatomic,strong)UIButton   *visitAddressLbl;
@property(nonatomic,strong)UITextView *visitRecordTV;
@property(nonatomic,strong)UIButton   *saveBtn;
@property(nonatomic,strong)UIButton   *qiandaoBtn;

@property(nonatomic,strong)VisitModel * model;


@end

@implementation VisitDetailViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton = YES;
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:@"拜访详情"];
    [self registerForKeyboardNotifications];
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    _basicArray = @[@"拜访日期",@"公司名称",@"预约地址",@"拜访对象",@"拜访类型"];
    
    _model = [[VisitModel alloc] init];
    _model.visitId = _visitId;
    //[self.view makeToastActivity];
    
    [self createUI];
}

- (void)createUI{
    
    //CGRect *rect = self.view.frame;
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH)];
    scrollView.showsVerticalScrollIndicator=NO;
    scrollView.backgroundColor = graySectionColor;
    [self.view addSubview:scrollView];
    
    DownbgView = [[UIView alloc] initWithFrame:CGRectMake(0, KSCreenH - 80 - 64, KSCreenH, 80)];
    DownbgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:DownbgView];
    
    _saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(LEFTWIDTH, 10, KSCreenW-2*LEFTWIDTH, 60)];
    
    [_saveBtn setTitle:@"确认保存" forState:UIControlStateNormal];
    [_saveBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal"] forState:UIControlStateNormal];
    _saveBtn.hidden = YES;
    [_saveBtn addTarget:self action:@selector(saveRecord:) forControlEvents:UIControlEventTouchUpInside];
    [DownbgView addSubview:_saveBtn];
    
    _qiandaoBtn = [[UIButton alloc]initWithFrame:CGRectMake(LEFTWIDTH, 10, KSCreenW-2*LEFTWIDTH, 60)];
    _qiandaoBtn.titleLabel.font = [UIFont systemFontOfSize:17.0];
    
    //    [_qiandaoBtn setTitle:@"签到" forState:UIControlStateNormal];
    //    [_qiandaoBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_green_normal"] forState:UIControlStateNormal];
    
    
    _qiandaoBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    
    //    [_qiandaoBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal"] forState:UIControlStateNormal];
    _qiandaoBtn.tag = 1;
    [_qiandaoBtn addTarget:self action:@selector(CheckinClick:) forControlEvents:UIControlEventTouchUpInside];
    [DownbgView addSubview:_qiandaoBtn];
    UIView *linev1 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW, 1) withBackgroudColor:grayLineColor];
    [DownbgView addSubview:linev1];
    
    
    [self initListView];
    
}

//签到按钮
- (void)CheckinClick:(UIButton *)butt
{
    //    NSDictionary * params1 = [NSDictionary dictionaryWithObjectsAndKeys:@(UID), @"uid", TOKEN, @"token",@(_visitId), @"id", _visitRecordTV.text,@"content", nil];
    //    //    NSLog(@"%@",params1);
    //    AFHTTPRequestOperationManager * manager1 = [AFHTTPRequestOperationManager manager];
    //    manager1.requestSerializer.timeoutInterval = 20;
    //    [manager1 POST:SIGN_IN_VISIT_URL parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        [self.view hideToastActivity];
    //        NSLog(@"GET_VISIT_DETAIL_URL:%@",responseObject);
    //        int code = [[(NSDictionary *)responseObject objectForKey:@"code"] intValue];
    //        if(code != 100)
    //        {
    //            NSString * message = [(NSDictionary *)responseObject objectForKey:@"message"];
    //            [self.view makeToast:message];
    //            NSLog(@"%@",message);
    //        }else{
    //            [self.view makeToast:@"增加成功"];
    //            _saveBtn.hidden = YES;
    //            [self goToBack];
    //        }
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        NSLog(@"%@",error);
    //        [self.view hideToastActivity];
    //    }];
    
    SignInSelectViewController *vc = [[SignInSelectViewController alloc] init];
    vc.model = self.model;
    vc.butttag = (int)butt.tag;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)initListView{
    CGFloat labelH = 20;
    CGFloat tfH    = 20;
    //    CGFloat tfY    = 20+ labelH;
    CGFloat tfW    = KSCreenW - LEFTWIDTH*8-10;
    
    upBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, KSCreenW, CELLHEIGHT4*5)];
    upBgView.backgroundColor = [UIColor whiteColor];
    UIView *line5 = [ViewTool getLineViewWith:CGRectMake(0, upBgView.height-1, KSCreenW , 1) withBackgroudColor:grayLineColor];
    
    [downBgView addSubview:line5];
    [scrollView addSubview:upBgView];
    
    downBgView = [[UIView alloc] initWithFrame:CGRectMake(0, upBgView.maxY , KSCreenW, tfH*7+20)];
    downBgView.backgroundColor = [UIColor whiteColor];
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, KSCreenW , 1) withBackgroudColor:UIColorFromRGB(0xe2e1e6)];
    
    UIView *line4 = [ViewTool getLineViewWith:CGRectMake(0, 19, KSCreenW , 1) withBackgroudColor:UIColorFromRGB(0xe2e1e6)];
    
    line2 = [ViewTool getLineViewWith:CGRectMake(0, downBgView.height-1, KSCreenW , 1) withBackgroudColor:UIColorFromRGB(0xe2e1e6)];
    [downBgView addSubview:line1];
    [downBgView addSubview:line4];
    [downBgView addSubview:line2];
    
    [scrollView addSubview:downBgView];
    
//    UIView *line = [ViewTool getLineViewWith:CGRectMake(0, downBgView.y-19, KSCreenW , 1) withBackgroudColor:UIColorFromRGB(0xe2e1e6)];
//    [self.view addSubview:line];
    
    for (int i = 0; i<_basicArray.count; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(LEFTWIDTH, 20+CELLHEIGHT4*i+15, 80, labelH) WithTitle:_basicArray[i] WithFontSize:14.0f WithTitleColor:blackFontColor WithTextAlignment:NSTextAlignmentLeft];
        [ViewTool setLableFont14:label];
        //        if (i == _basicArray.count-1) {
        //            label.frame = CGRectMake(LEFTWIDTH, 20+CELLHEIGHT4*i+tfH + 20, 80, labelH);
        //        }
        [scrollView addSubview:label];
        
        if (i < _basicArray.count) {
            UIView *line = [ViewTool getLineViewWith:CGRectMake(LEFTWIDTH, (CELLHEIGHT4)*i-1 +20, KSCreenW , 1) withBackgroudColor:UIColorFromRGB(0xe2e1e6)];
            if (i == 0) {
                line.frame = CGRectMake(0, (CELLHEIGHT4)*i-1 +20 , KSCreenW , 1);
            }
            [scrollView addSubview:line];
        }
    }
    UILabel *areaLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 1, KSCreenW , 18)];
    areaLab.backgroundColor = graySectionColor;
    [downBgView addSubview:areaLab];
    
    _visitDateLbl = [self addLableWithFrame:CGRectMake(LEFTWIDTH*8, 35, tfW, tfH) AndStr:@""  AndTextColor:grayFontColor];
    _companyLbl = [self addLableWithFrame:CGRectMake(_visitDateLbl.x, _visitDateLbl.maxY + CELLHEIGHT4-tfH, tfW, tfH) AndStr:@""  AndTextColor:grayFontColor];
    
    _visitAddressLbl = [[UIButton alloc] initWithFrame:CGRectMake(_visitDateLbl.x, _companyLbl.maxY + CELLHEIGHT4-tfH , tfW, tfH)];
    _visitAddressLbl.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _visitAddressLbl.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [_visitAddressLbl setTitleColor:grayFontColor forState:UIControlStateNormal];
    _visitAddressLbl.titleLabel.font = [ViewTool getFont14];
    //    [_visitAddressLbl addTarget:self action:@selector(jumpToMap) forControlEvents:UIControlEventTouchUpInside];
    
    _visitObjectLbl = [self addLableWithFrame:CGRectMake(_visitDateLbl.x, _visitAddressLbl.maxY + CELLHEIGHT4-tfH, tfW, tfH) AndStr:@""  AndTextColor:grayFontColor];
    
    _visitTypeLbl = [self addLableWithFrame:CGRectMake(_visitDateLbl.x, _visitObjectLbl.maxY + CELLHEIGHT4-tfH, tfW, tfH) AndStr:@""  AndTextColor:grayFontColor];
    
    //    UIButton  *btn = [[UIButton alloc] initWithFrame:CGRectMake(KSCreenW - LEFTWIDTH - 30, _visitAddressLbl.y, 23, 23)];
    
    //    [btn setBackgroundImage:[UIImage imageNamed:@"定位蓝色"] forState:UIControlStateNormal];
    //    [scrollView addSubview:btn];
    //    [btn addTarget:self action:@selector(jumpToMap) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *visitRecordLab = [self addLableWithFrame:CGRectMake(LEFTWIDTH, 35 , 80, tfH) AndStr:@"拜访纪要"  AndTextColor:grayFontColor];
    
    remaind = [self addLableWithFrame:CGRectMake(LEFTWIDTH, downBgView.maxY +5, KSCreenW, tfH) AndStr:@"“拜访纪要”可随时编辑更改"  AndTextColor:grayFontColor];
    
    _visitRecordTV = [[UITextView alloc] initWithFrame:CGRectMake(LEFTWIDTH*8, 30, KSCreenW - 9*LEFTWIDTH, tfH*6 - 5)];
    
    _visitRecordTV.textColor = blackFontColor;
    //_visitRecordTV.backgroundColor = [UIColor redColor];
    _visitRecordTV.returnKeyType = UIReturnKeyDefault;
    _visitRecordTV.delegate = self;
    
    _visitRecordTV.userInteractionEnabled = YES;
    _visitRecordTV.font = [ViewTool getFont14];
    
    //刷新请求的数据
    if(_model.visittime == nil){
        _visitDateLbl.text = [self cutTimeString:_model.ordertime];
    }else{
        _visitDateLbl.text = [self cutTimeString:_model.visittime];
    }
    _companyLbl.text = _model.company;
    _visitObjectLbl.text = _model.contactname;
    NSLog(@"kkkkkkkkkkkkkk-----------  %@",_model.contactname);
    _visitTypeLbl.text = _model.visittype;
    [_visitAddressLbl setTitle:_model.address forState:UIControlStateNormal];
    _visitRecordTV.text = _model.content;
     endContent.text = _model.content;
    
    [scrollView addSubview:_visitDateLbl];
    [scrollView addSubview:_companyLbl];
    [scrollView addSubview:_visitObjectLbl];
    [scrollView addSubview:_visitTypeLbl];
    [scrollView addSubview:_visitAddressLbl];
    [scrollView addSubview:remaind];
    
    [downBgView addSubview:visitRecordLab];
    [downBgView addSubview:_visitRecordTV];
    
    [self reloadData];
    
    //签到 和 签退
    //    checkBG = [[UIView alloc] initWithFrame:CGRectMake(0, scrollView.height - 80, KSCreenW, 80)];
    //    checkBG.backgroundColor = [UIColor whiteColor];
    //    [scrollView addSubview:checkBG];
    //
    //    UIButton *checkButton = [[UIButton alloc] initWithFrame:CGRectMake(7.5, 5, KSCreenW - 15, 70)];
    //    //[checkButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    //    checkButton.backgroundColor = redBackColor;
    //    [checkButton setTitle:@"签到" forState:UIControlStateNormal];
    //    [checkButton addTarget:self action:@selector(GoToSignInVC) forControlEvents:UIControlEventTouchUpInside];
    //    [checkBG addSubview:checkButton];
    
}

-(UILabel *)addLableWithFrame:(CGRect)frame AndStr:(NSString *)title AndTextColor:(UIColor *)color
{
    UILabel *textL=[[UILabel alloc]initWithFrame:frame];
    
    textL.text = title;
    textL.userInteractionEnabled = YES;
    textL.textColor = color;
    [ViewTool setLableFont14:textL];
    return textL;
}

- (void)refreshData{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateStr;
    
    if(_model.visittime == nil){
        _visitDateLbl.text = [self cutTimeString:_model.ordertime];
        dateStr = _model.ordertime;
    }else{
        NSDate *orderDate = [dateFormatter dateFromString:_model.ordertime];
        NSDate *visitDate = [dateFormatter dateFromString:_model.visittime];
        
        int d = [DateTool compareOneDay:orderDate withAnotherDay:visitDate];
        
        if (d == 1) {
            
            _visitDateLbl.text = [self cutTimeString:_model.ordertime];
            dateStr = _model.ordertime;
        }else{
            _visitDateLbl.text = [self cutTimeString:_model.visittime];
            dateStr = _model.visittime;
        }
    }
    
    NSDate *date = [dateFormatter dateFromString:dateStr];
    
    int d = [DateTool compareOneDay:date withAnotherDay:[NSDate date]];
//    NSLog(@"%d*-*-*-*-*-*-*-*-*-",d);
    if (d == -1) {
//        _visitRecordTV.editable = NO;//不可编辑
        isAge = YES;
        
        DownbgView.hidden = YES;
//        canEdit = NO;
        if (!_canChangeText) {
            canEdit = NO;
        }else{
            canEdit = YES;
        }
        
    }else{
//        _visitRecordTV.editable = YES;
        
        if (!_canChangeText) {
            canEdit = NO;
            DownbgView.hidden = YES;
        }else{
           
            [self isSigned];
            canEdit = YES;
        }
        isAge = NO;
//        [self initFeedText];
    }
    
    _companyLbl.text = _model.company;
    _visitObjectLbl.text = _model.contactname;
    _visitTypeLbl.text = _model.visittype;
    [_visitAddressLbl setTitle:_model.address forState:UIControlStateNormal];
    _visitRecordTV.text = _model.content;
   
    if (isSignin == 1) {
        [self creatSignView:1];
    }
    if (isSignin == 1&&isSignout == 1) {
        [self creatSignView:2];
    }
    
    //    CGSize size = [@"Hello" boundingRectWithSize:CGSizeMake(KSCreenW - 2*LEFTWIDTH, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [ViewTool getFont14],NSForegroundColorAttributeName : blackFontColor} context:nil].size;
    //    CGFloat height = size.height;
    //
    //    CGSize size1 = [_model.content boundingRectWithSize:CGSizeMake(KSCreenW - 2*LEFTWIDTH, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [ViewTool getFont14],NSForegroundColorAttributeName : blackFontColor} context:nil].size;
    //    if (size1.height < height) {
    //        _visitRecordTV.height = height;
    //    }else{
    //        _visitRecordTV.height = size1.height;
    //    }
    NSLog(@"%@*-*-*-*-*-*-*-*-*-%@   ",_model.signinimg,_model.signinaddress);
    
    
    
    
    lon = [[DataTool changeType:_model.lon] floatValue];
    lat = [[DataTool changeType:_model.lat] floatValue];
    
}

//
- (void)isSigned
{
    if (isSignin == 0) {
        [_qiandaoBtn setTitle:@"签到" forState:UIControlStateNormal];
        [_qiandaoBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_green_normal"] forState:UIControlStateNormal];
        if (isAge == NO) {
            DownbgView.hidden = NO;
            _qiandaoBtn.hidden = NO;
        }
        else{
            DownbgView.hidden = YES;
            _qiandaoBtn.hidden = YES;
        }
    }
    if (isSignin == 1) {
        [_qiandaoBtn setTitle:@"签退" forState:UIControlStateNormal];
        [_qiandaoBtn setBackgroundImage:[UIImage imageNamed:@"HY_btn_red_normal"] forState:UIControlStateNormal];
        [self creatSignView:1];
        if (isAge == NO) {
            DownbgView.hidden = NO;
            _qiandaoBtn.hidden = NO;
        }else{
            DownbgView.hidden = YES;
            _qiandaoBtn.hidden = YES;
        }
        
    }
    if (isSignin == 1&&isSignout == 1) {
        [_qiandaoBtn removeFromSuperview];
        DownbgView.hidden = YES;
        [self creatSignView:2];
    }
    
}

//增加 签到 签退
- (void)creatSignView:(int)height
{
    signView = [[UIView alloc] initWithFrame:CGRectMake(0, upBgView.maxY, KSCreenW, 100*height)];
    signView.backgroundColor = [UIColor whiteColor];
    
    downBgView.frame = CGRectMake(0, signView.maxY  , KSCreenW, 20*7 + 20);
    remaind.frame = CGRectMake(LEFTWIDTH, downBgView.maxY+10, KSCreenW, 20);
    
    scrollView.contentSize = CGSizeMake(KSCreenW, downBgView.maxY +50 + 64);
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(LEFTWIDTH, 0, KSCreenW , 1) withBackgroudColor:grayLineColor];
    [signView addSubview:line];
    
//    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(LEFTWIDTH, 100-1, KSCreenW , 1) withBackgroudColor:grayLineColor];
//    [signView addSubview:line1];
    
    UILabel *signin = [self addLableWithFrame:CGRectMake(LEFTWIDTH, 40, 80, 20) AndStr:@"签到详情"  AndTextColor:blackFontColor];
    UIImageView *signinImage = [[UIImageView alloc] initWithFrame:CGRectMake(signin.maxX+10, 10, 80, 80)];
    [signinImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",LoadImageUrl,_model.signinimg]]];
    UILabel *signinaddress = [self addLableWithFrame:CGRectMake(signinImage.maxX+10, 30, KSCreenW - signinImage.maxX-30, 20) AndStr:[NSString stringWithFormat:@"%@",_model.signinaddress]  AndTextColor:grayFontColor];
    UILabel *signintime = [self addLableWithFrame:CGRectMake(signinImage.maxX+10, 50, 80, 20) AndStr:[NSString stringWithFormat:@"%@",_model.signintime]  AndTextColor:grayFontColor];
    
    _qiandaoBtn.tag = 2;
    
    [signView addSubview:signin];
    [signView addSubview:signinImage];
    [signView addSubview:signinaddress];
    [signView addSubview:signintime];
    
    if (height == 2){
        UIView *line = [ViewTool getLineViewWith:CGRectMake(LEFTWIDTH, 100-1, KSCreenW , 1) withBackgroudColor:grayLineColor];
//        UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, 200-1, KSCreenW , 1) withBackgroudColor:grayLineColor];
        [signView addSubview:line];
//        [signView addSubview:line3];
        
        UILabel *signout = [self addLableWithFrame:CGRectMake(LEFTWIDTH, line.maxY+40, 80, 20) AndStr:@"签退详情"  AndTextColor:blackFontColor];
        
        UIImageView *signoutImage = [[UIImageView alloc] initWithFrame:CGRectMake(signout.maxX+10, line.maxY+10, 80, 80)];
        [signoutImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",LoadImageUrl,_model.signoutimg]]];
        
        UILabel *signoutaddress = [self addLableWithFrame:CGRectMake(signoutImage.maxX+10, line.maxY+30, KSCreenW - signoutImage.maxX-30, 20) AndStr:[NSString stringWithFormat:@"%@",_model.signoutaddress]  AndTextColor:grayFontColor];
        
        UILabel *signouttime = [self addLableWithFrame:CGRectMake(signoutImage.maxX+10, line.maxY+50, 80, 20) AndStr:[NSString stringWithFormat:@"%@",_model.signouttime]  AndTextColor:grayFontColor];
        
        [signView addSubview:signout];
        [signView addSubview:signoutImage];
        [signView addSubview:signoutaddress];
        [signView addSubview:signouttime];
    }
    
    [scrollView addSubview:signView];
}

- (void)reloadData{
    [self.view makeToastActivity];
    
    NSDictionary * params1 = [NSDictionary dictionaryWithObjectsAndKeys:@(UID), @"uid", TOKEN, @"token",@(_visitId), @"id", nil];
    NSLog(@"%@",params1);
    AFHTTPRequestOperationManager * manager1 = [AFHTTPRequestOperationManager manager];
    manager1.requestSerializer.timeoutInterval = 20;
    [manager1 POST:GET_VISIT_DETAIL_URL parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view hideToastActivity];
        NSLog(@"GET_VISIT_DETAIL_URL:%@",responseObject);
        int code = [[(NSDictionary *)responseObject objectForKey:@"code"] intValue];
        if(code != 100)
        {
            NSString * message = [(NSDictionary *)responseObject objectForKey:@"message"];
            [self.view makeToast:message];
        }else{
            isSignin = [[(NSDictionary *)responseObject objectForKey:@"isSignin"] intValue];
            isSignout = [[(NSDictionary *)responseObject objectForKey:@"isSignout"] intValue];
            NSDictionary * visitMap = [(NSDictionary *)responseObject objectForKey:@"visitMap"];
            NSDictionary * sign = [(NSDictionary *)responseObject objectForKey:@"sign"];
            
            [_model setValuesForKeysWithDictionary:visitMap];
            if (isSignin == 1) {
                [_model setValuesForKeysWithDictionary:sign];
            }
                        
            [self refreshData];
            [SVProgressHUD dismiss];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.view hideToastActivity];
        [SVProgressHUD dismiss];
        [self.view makeToast:error.localizedDescription];

    }];
}

- (void) initFeedText{
    //在弹出的键盘上面加一个view来放置退出键盘的Done按钮
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, KSCreenW, 40)];
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
    doneButton.tintColor = [UIColor blackColor];
    
    [topView setItems:buttonsArray];
    [_visitRecordTV setInputAccessoryView:topView];
}

//关闭键盘
-(void) dismissKeyBoard{
    [_visitRecordTV resignFirstResponder];
    //    if(_model.content.length < _visitRecordTV.text.length){
    if (_model.content.length < _visitRecordTV.text.length) {
        _saveBtn.hidden = NO;
    }else{
        _saveBtn.hidden = YES;
    }
}

- (void)jumpToMap
{
    MapClientViewController * mapVC = [[MapClientViewController alloc] init];
    if (lon == 0&&lat == 0) {
        mapVC.result = 1;
    }else{
        mapVC.locationLongide = [NSString stringWithFormat:@"%f",lon];
        mapVC.locationLatitude =  [NSString stringWithFormat:@"%f",lat];
    }
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
//    NSLog(@"%@++++++-------",mapVC.locationLatitude);
    
}
- (NSString *)cutTimeString:(NSString *)dateString
{
    
    NSString   *timeS;
    if (dateString.length>15) {
        timeS = [dateString substringToIndex:16];
    }
    return timeS;
}
//提交按钮
- (void)saveRecord:(UIButton *)btn{
    
    if(_model.content.length >= _visitRecordTV.text.length){
        [self.view makeToast:@"请增加访谈纪要"];
        return;
    }
    isEditing = NO;
    NSDictionary * params1 = [NSDictionary dictionaryWithObjectsAndKeys:@(UID), @"uid", TOKEN, @"token",@(_visitId), @"id", _visitRecordTV.text,@"content", nil];
    //    NSLog(@"%@",params1);
    AFHTTPRequestOperationManager * manager1 = [AFHTTPRequestOperationManager manager];
    manager1.requestSerializer.timeoutInterval = 20;
    [manager1 POST:UPDATE_VISIT_CONTENT_URL parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view hideToastActivity];
        NSLog(@"GET_VISIT_DETAIL_URL:%@",responseObject);
        int code = [[(NSDictionary *)responseObject objectForKey:@"code"] intValue];
        if(code != 100)
        {
            NSString * message = [(NSDictionary *)responseObject objectForKey:@"message"];
            [self.view makeToast:message];
            NSLog(@"%@",message);
        }else{
            [self.view makeToast:@"增加成功"];
            _saveBtn.hidden = YES;
            
            [self isSigned];
            [self reloadData];
            
            //            [self goToBack];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.view hideToastActivity];
    }];
}

- (void)goToBack{
    if(isEditing == YES){
        NSString *str = [NSString stringWithFormat:@"访谈纪要未保存是否退出？"];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleActionSheet];
        //添加Button
        [alertController addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[self navigationController] popViewControllerAnimated:YES];
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [[self navigationController] popViewControllerAnimated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}
- (void)viewWillAppear:(BOOL)animated
{
    [SVProgressHUD showWithStatus:@"加载中"];
    [self createUI];
    NSLog(@"--------------       000000 -----back");
    [super viewWillAppear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//监听事件
- (void)handleKeyboardDidShow:(NSNotification*)paramNotification
{
    
    NSDictionary *usrInfoDict = paramNotification.userInfo;
    CGRect keyRect = [usrInfoDict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat showtime = [usrInfoDict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSLog(@"%f",keyRect.origin.y );
    //    scrollView.contentInset=UIEdgeInsetsMake(0, 0,keyRect.size.height, 0);
    if(_visitRecordTV.isFirstResponder){
        
        diff = fabs( keyRect.origin.y - CGRectGetMaxY(_visitRecordTV.frame) );
        NSLog(@"%f",CGRectGetMaxY(_visitRecordTV.frame));
        
        if (keyRect.origin.y < (CGRectGetMaxY(_visitRecordTV.frame) )) {
            [UIView animateWithDuration:showtime animations:^{
                //                self.view.transform = CGAffineTransformMakeTranslation(0, -diff);
                scrollView.frame = CGRectMake(0, -diff , KSCreenW, KSCreenH );
                //                scrollView.transform = CGAffineTransformMakeTranslation(0, -diff);
                if(!_saveBtn.hidden){
                    
                    scrollView.transform = CGAffineTransformMakeTranslation(0, -diff);
                    //                    scrollView.frame = CGRectMake(0, -diff + 64, KSCreenW, KSCreenH - 64-TabbarH);
                }
            }];
        }
    }
    
}

- (void)handleKeyboardDidHidden:(NSNotification *)noti
{
    NSDictionary *usrInfoDict = noti.userInfo;
    CGFloat showtime = [usrInfoDict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //    scrollView.contentInset=UIEdgeInsetsZero;
    [UIView animateWithDuration:showtime animations:^{
        //                self.view.transform = CGAffineTransformMakeTranslation(0, -diff);
        //        scrollView.transform = CGAffineTransformMakeTranslation(0, -diff);
        scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH );
        if(!_saveBtn.hidden){
            scrollView.frame = CGRectMake(0, 0, KSCreenW, KSCreenH -TabbarH);
        }
    }];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardDidShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleKeyboardDidHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)textViewDidChange:(UITextView *)textView{
    
    CGSize size = [textView.text boundingRectWithSize:CGSizeMake(KSCreenW - 2*LEFTWIDTH, MAXFLOAT) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [ViewTool getFont14],NSForegroundColorAttributeName : blackFontColor} context:nil].size;
    
        if (size.height > 115) {
                scrollView.y = -(size.height - 115);
                textView.height = size.height-15;
                downBgView.height = size.height+25;
                scrollView.height = KSCreenH + (size.height - 115);
           
            }else{
                scrollView.y = 0;
                textView.height = 115;
                downBgView.height = 160;
                scrollView.height = KSCreenH;
            }
    
            scrollView.contentSize = CGSizeMake(KSCreenW, downBgView.maxY +50 + 64);
            line2.frame = CGRectMake(0, downBgView.height-1, KSCreenW , 1);
            remaind.frame = CGRectMake(LEFTWIDTH, downBgView.maxY+10, KSCreenW, 20);
    
        DownbgView.hidden = NO;
        _saveBtn.hidden = NO;
        _qiandaoBtn.hidden = YES;

}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    
    if ([text isEqualToString:@"\n"]) {
      
    }else{
        NSLog(@"12121:%@---- %@=====------%@",endContent.text,_visitRecordTV.text,_model.content);
        
        if ([text length] == 0) {
            if(_model.content.length < _visitRecordTV.text.length){
                isEditing = YES;
                if (isAge == NO) {
                    DownbgView.hidden = NO;
                    _saveBtn.hidden = NO;
                }
                _qiandaoBtn.hidden = YES;
                //                [DownbgView bringSubviewToFront:_saveBtn];
                
            }else{
                
                [self isSigned];
                isEditing = NO;
                //                [DownbgView bringSubviewToFront:_qiandaoBtn];
                return NO;
            }
        }
    }
    
    return YES;
    
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (!canEdit) {
        return NO;
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"12121");
    [_visitRecordTV resignFirstResponder];
    [self.view endEditing:YES];
}

- (void)GoToSignInVC
{
    SignInViewController *vc = [[SignInViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end